<?php

namespace app\admin\controller\develop;

use app\admin\model\entrepot\Deliver;
use app\admin\model\statistics\Acquisitionschemedetail;
use app\admin\model\statistics\Materialplanaudit;
use app\admin\model\statistics\Orderdetail;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 领料方案
 *
 * @icon fa fa-circle-o
 */
class Acuisitionscheme extends Backend
{

    /**
     * Acuisitionscheme模型对象
     * @var \app\admin\model\develop\Acuisitionscheme
     */
    protected $model = null;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\develop\Acuisitionscheme;
        //$this->view->assign("statusList", $this->model->getStatusList());
        $ids = $this->request->get("ids");
        if($ids){
            $getStatusList=array(
                '0'=>'待发料',
                '1'=>'已发料',
                '2'=>'退料'
            );
        }else{
            $getStatusList=$this->model->getStatusList();
        } 
        $this->view->assign("statusList", $getStatusList);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['order','detail','colour','employee'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','createtime','updatetime','status']);
                $row->visible(['order']);
				$row->getRelation('order')->visible(['order_no','schedule']);
				$row->visible(['detail']);
				$row->getRelation('detail')->visible(['trademark_printing','abbreviation','quantity','cumulative_quantity']);
				$row->visible(['colour']);
				$row->getRelation('colour')->visible(['name']);
				$row->visible(['employee']);
				$row->getRelation('employee')->visible(['name']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加 by lhq
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                //数据处理
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    //如果
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function add_detail($ids){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //领料明细明细模型
                $acquisitionschemedetail = new Acquisitionschemedetail();
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $result = true;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $acquisitionschemedetail->validateFailException(true)->validate($validate);
                    }
                    //添加数据到领料明细表中
                    if (!$acquisitionschemedetail->allowField(true)->save($params)){
                        Db::rollback();
                        $this->error('操作失败');
                    }
                    $acquisition_scheme_detail_id = $acquisitionschemedetail->getLastInsID();

                    //获取领料主表详情
                    $acquisition_scheme = new \app\admin\model\develop\Acuisitionscheme();
                    $acquisition_scheme_where['id'] = $params['acquisition_scheme_id'];
                    $acquisition_scheme_data = collection($acquisition_scheme->where($acquisition_scheme_where)->limit(1)->select())->toArray();

                    //获取订单商品详情
                    $order_detail = new \app\admin\model\statistics\Orderdetail;
                    $order_detail_where['id'] = $acquisition_scheme_data[0]['order_detail_id'];
                    $order_detail_data = collection($order_detail->where($order_detail_where)->select())->toArray();
                    if (count($order_detail_data) == 0){
                        Db::rollback();
                        $this->error(__('获取订单信息失败！'));
                    }

                    $cur_quantity = intval($params['quantity']);//本次数量
                    $cumulative_quantity = intval($order_detail_data[0]['cumulative_quantity']); //累计分配数量
                    $order_quantity = intval($order_detail_data[0]['quantity']);//订单总数量
                    if($cur_quantity + $cumulative_quantity  > $order_quantity){
                        $this->error('操作失败，当前分配数量与累计分配之和不能大于订单数量');
                    }else{
                        //更新累计分配数量
                        $order_detail_up_where['id'] = $order_detail_data[0]['id'];
                        $res2 = $order_detail->where($order_detail_up_where)->setInc('cumulative_quantity',$cur_quantity);

                        if (!$res2) {
                            Db::rollback();
                            $this->error(__('更新累计分配数量失败'));
                        }

                        //更新主表分配状态
                        $acquisition_scheme_up_where['id'] = $params['acquisition_scheme_id'];
                        $this->model->where($acquisition_scheme_up_where)->setField('status',$cur_quantity + $cumulative_quantity == $order_quantity?2:1);

                        //新增待发料数据
                        $deliver_data['order_id'] = $acquisition_scheme_data[0]['order_id'];
                        $deliver_data['order_detail_id'] = $acquisition_scheme_data[0]['order_detail_id'];
                        $deliver_data['colour_id'] = $acquisition_scheme_data[0]['colour_id'];
                        $deliver_data['employee_id'] = $params['employee_id'];
                        $deliver_data['material_plan_id'] = $acquisition_scheme_data[0]['material_plan_id'];
                        $deliver_data['acquisition_scheme_detail_id'] = $acquisition_scheme_detail_id;
                        $deliver_data['quantity'] = $cur_quantity;

                        //计算物料重量数据
                        //数量*投料重量*（长档比例*物料比例 + 短档比例*物料比例）
                        //获取物料方案详情
                        $materialplan = new \app\admin\model\statistics\Materialplan;
                        $materialplan_where['id'] = $acquisition_scheme_data[0]['material_plan_id'];
                        $materialplan_data = collection($materialplan->where($materialplan_where)->limit(1)->select())->toArray();


                        $materiallist =[];
                        $long = '';
                        $short = '';
                        if(boolval($materialplan_data[0]['longlist'])) $long = \GuzzleHttp\json_decode($materialplan_data[0]['longlist'],true);

                        if(boolval($materialplan_data[0]['shortlist'])) $short = \GuzzleHttp\json_decode($materialplan_data[0]['shortlist'],true);

                        if($long && $short){
                            foreach ($long as $k=>$v){
                                foreach ($short as $k2=>$v2){
                                    if($v['material']==$v2['material'] && $v['material_colour']==$v2['material_colour']){
                                        $data['weight'] = round($cur_quantity*$materialplan_data[0]['feeding_weight']
                                            *($materialplan_data[0]['long_ratio']/100*$v['ratio']/100
                                                + $materialplan_data[0]['short_ratio']/100*$v2['ratio']/100),2);
                                        if(!isset($materiallist[$v2['material'].$v2['material_colour']])){
                                            $data['material'] = $v2['material'];
                                            $data['material_colour'] = $v2['material_colour'];
                                            $materiallist[$v2['material'].$v2['material_colour']]=$data;
                                        }else{
                                            $materiallist[$v2['material'].$v2['material_colour']]['weight'] = $data['weight'];
                                        }

                                        //  p('计算公式='.$cur_quantity.'*'.$materialplan_data[0]['feeding_weight'].
//                                        '*('.$materialplan_data[0]['long_ratio'].'/100*'.$v['ratio'].'/100
//                                            + '.$materialplan_data[0]['short_ratio'].'/100*'.$v2['ratio'].'/100)');

                                    }else{ //添加两条

                                        $data['material'] = $v2['material'];
                                        $data['material_colour'] = $v2['material_colour'];
                                        $data['weight'] = round($cur_quantity*$materialplan_data[0]['feeding_weight']*$materialplan_data[0]['short_ratio']/100*$v2['ratio']/100,2);

                                        if(!isset($materiallist[$v2['material'].$v2['material_colour']])){
                                            $data['weight'] =  $data['weight'];
                                            $materiallist[$v2['material'].$v2['material_colour']]=$data;
                                        }else{
                                            foreach ($materiallist as $key=>$val){
                                                if($val['material'] == $data['material'] && $val['material_colour'] == $data['material_colour']){
                                                    $data['weight'] +=  $data['weight'];
                                                }
                                            }
                                        }

                                        $data2['material'] = $v['material'];
                                        $data2['material_colour'] = $v['material_colour'];
                                        $data2['weight'] = round($cur_quantity*$materialplan_data[0]['feeding_weight']*$materialplan_data[0]['long_ratio']/100*$v['ratio']/100,2);
                                        if(!is_set_material($data2,$materiallist)){
                                            $data2['weight'] =  $data2['weight'];
                                            $materiallist[$v['material'].$v['material_colour']] = $data2;
                                        }else{
                                            foreach ($materiallist as $key=>$val){
                                                if($val['material'] == $data2['material'] && $val['material_colour'] == $data2['material_colour']){
                                                    $data['weight'] +=  $data2['weight'];
                                                }

                                            }
                                        }

                                    }
                                }
                            }
                        }
                        if($long && !$short){
                            foreach ($long as $k=>$v){
                                $data2['material'] = $v['material'];
                                $data2['material_colour'] = $v['material_colour'];
                                $data2['weight'] = round($cur_quantity*$materialplan_data[0]['feeding_weight']*$materialplan_data[0]['long_ratio']/100*$v['ratio']/100,2);
                                if(!is_set_material($data2,$materiallist)){
                                    $data2['weight'] =  $data2['weight'];
                                    $materiallist[$v['material'].$v['material_colour']] = $data2;
                                }else{
                                    foreach ($materiallist as $key=>$val){
                                        if($val['material'] == $data2['material'] && $val['material_colour'] == $data2['material_colour']){
                                            $data['weight'] +=  $data2['weight'];
                                        }

                                    }
                                }
                            }
                        }
                        if(!$long && $short){
                            foreach ($short as $k2=>$v2) {
                                $data['material'] = $v2['material'];
                                $data['material_colour'] = $v2['material_colour'];
                                $data['weight'] = round($cur_quantity * $materialplan_data[0]['feeding_weight'] * $materialplan_data[0]['short_ratio'] / 100 * $v2['ratio'] / 100, 2);
                                if (!isset($materiallist[$v2['material'] . $v2['material_colour']])) {
                                    $data['weight'] = $data['weight'];
                                    $materiallist[$v2['material'] . $v2['material_colour']] = $data;
                                } else {
                                    foreach ($materiallist as $key => $val) {
                                        if ($val['material'] == $data['material'] && $val['material_colour'] == $data['material_colour']) {
                                            $data['weight'] += $data['weight'];
                                        }
                                    }
                                }
                            }
                        }
                        $deliver_data['acquisition_scheme_id'] = $params['acquisition_scheme_id'];
                        $deliver_data['materiallist'] = \GuzzleHttp\json_encode($materiallist,JSON_UNESCAPED_UNICODE);

                        $deliver = new Deliver();

                        if(!$deliver->save($deliver_data)){
                            Db::rollback();
                            $this->error('添加发料数据失败');
                        }

                    }

                    Db::commit();
                    $this->success();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $where['a.id'] = $ids;
        $list = Db::name('acquisition_scheme')->alias('a')
            ->join('order o','o.id=a.order_id')
            ->join('order_detail od','od.id=a.order_detail_id')
            ->join('colour c','c.id=od.colour_id')
            ->where($where)
            ->field('a.id,o.order_no,c.name as colour_name,od.trademark_printing,od.abbreviation,od.quantity,od.cumulative_quantity')
//            ->fetchSql()
            ->select();

//        p($list);
        if($list){
            $list[0]['nocumulative'] = $list[0]['quantity'] - $list[0]['cumulative_quantity'];
            $this->assign('acuisitionschemeInfo',$list[0]);
        }

        return $this->view->fetch();
    }

    /**
     * @param $ids
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * 领料明细
     */
    public function show_detail($ids){
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['employee'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','quantity','createtime','updatetime','status']);
                $row->visible(['employee']);
                $row->getRelation('employee')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign('acquisition_scheme_id',$ids);
        return $this->view->fetch();
    }
}
